package com.zonhar.autofeed.common.device.hcsr04;

import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;

/**
 * 超声波测距驱动
 * @author Chenhua
 * @date 2023-04-13
 */
public class RangeSensor {

    GpioPinDigitalOutput firepulse;
    GpioPinDigitalInput result_pin;

    public RangeSensor(GpioPinDigitalOutput trigger, GpioPinDigitalInput result_pin) {
        this.firepulse = trigger;
        this.result_pin = result_pin;
    }

    /**
     * 触发距离传感器并返回结果
     */
    public double getRange() {
        long start = 0;
        long diff = 0;
        try {
            firepulse.high();
            Thread.sleep(10);
            firepulse.low();

            while (result_pin.isLow()) {
                start = System.nanoTime();
            }

            while (result_pin.isHigh()) {
            }
            diff = (System.nanoTime() - start) / 58000;
            return diff;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return -1;
    }
}